<?php
namespace Modules\Backstage\Controllers;

class TradeBuyController extends \Phalcon\Mvc\Controller {
	public function beforeExecuteRoute(\Phalcon\Mvc\Dispatcher $dispatcher) {
		$this -> response -> setStatusCode(200, 'OK') -> sendHeaders() -> setContentType('application/json', 'UTF-8');

		$service = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($service['code'] != 0) {
			$this -> response -> setJsonContent(['code'=>-1,'msg'=>$service['message'] ]) -> send();
			exit;
		}

		$this -> account::getAclInstance() -> check($this, $dispatcher, $service['model'] -> roles_id);
	}

	public function indexAction() {
		$query = $this -> request -> getQuery();
		if(!isset($query['page'])) {
			$query['page'] = 1;
		} else if($query['page'] <= 0)  {
			$query['page'] = 1;
		} else {
			$query['page'] = abs($query['page']);
		}

		if(!isset($query['limit'])) {
			$query['limit'] = 10;
		} else if($query['limit'] <= 0)  {
			$query['limit'] = 10;
		} else {
			$query['limit'] = abs($query['limit']);
		}

		$service = $this -> trade::getBuyLogicInstance() -> pager([], $query['limit'], $query['page']);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'pager' => $service['pager']]);
	}

	public function findFirstByIdAction($id) {
		$serviceBuy = $this -> trade::getBuyServiceInstance() -> findFirstById($id);
		if($serviceBuy['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceBuy['code'],'msg'=>'进货订单获取失败']);
		}

		$serviceUserBuy = $this -> user::getServiceInstance() -> findFirstById($serviceBuy['trade_buy'] -> from_user_id);
		if($serviceUserBuy['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUserBuy['code'],'msg'=>$serviceUserBuy['message']]);
		}

		$serviceSell = $this -> trade::getSellServiceInstance() -> findFirstById($serviceBuy['trade_buy'] -> trade_sell_id);
		if($serviceSell['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'trade_buy' => $serviceBuy['trade_buy'],'user_buy'=>$serviceUserBuy['user']]);
		}

		$serviceUserSell = $this -> user::getServiceInstance() -> findFirstById($serviceSell['trade_sell'] -> from_user_id);
		if($serviceUserSell['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUserSell['code'],'msg'=>$serviceUserSell['message']]);
		}
		if($serviceUserSell['user'] -> pid <= 0) {
			$serviceParentUserSell['user'] = [
				'cellphone' => '无推荐人'
			];
		} else {
			$serviceParentUserSell = $this -> user::getServiceInstance() -> findFirstById($serviceUserSell['user'] -> pid);
			if($serviceParentUserSell['code'] != 0) {
				$serviceParentUserSell['user'] = [
					'cellphone' => '无推荐人'
				];
			}
		}

		$serviceBankInfo = $this -> user::getBankInfoServiceInstance() -> findFirstById($serviceSell['trade_sell'] -> user_bank_info_id);
		if($serviceBankInfo['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceBankInfo['code'],'msg'=>'银行卡信息获取失败']);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'user_sell' =>$serviceUserSell['user'],'user_buy'=>$serviceUserBuy['user'],'parent_user_sell'=>$serviceParentUserSell['user'], 'trade_buy' => $serviceBuy['trade_buy'],'trade_sell'=>$serviceSell['trade_sell'],'user_bank_info' => $serviceBankInfo['user_bank_info']]);
	}

	public function matchIndexAction($id) {
		$findTradeBuy = $this -> trade::getBuyServiceInstance() -> findFirstById($id);
		if($findTradeBuy['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$findTradeBuy['code'],'msg'=>$findTradeBuy['message']]);
		}

		$query = $this -> request -> getQuery();
		if(!isset($query['page'])) {
			$query['page'] = 1;
		} else if($query['page'] <= 0)  {
			$query['page'] = 1;
		} else {
			$query['page'] = abs($query['page']);
		}

		if(!isset($query['limit'])) {
			$query['limit'] = 10;
		} else if($query['limit'] <= 0)  {
			$query['limit'] = 10;
		} else {
			$query['limit'] = abs($query['limit']);
		}

		$service = $this -> trade::getSellLogicInstance() -> match(['trade_buy' => $findTradeBuy['trade_buy']], $query['limit'], $query['page']);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'trade_buy' => $findTradeBuy['trade_buy'], 'pager' => $service['pager']]);
	}

	public function matchAction($id) {
		$post = $this -> request -> getPost();
		if(!isset($post['trade_sell_ids']) || empty($post['trade_sell_ids']) || !is_array($post['trade_sell_ids'])) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'请正确选择匹配订单!']);
		}

		$tradeSellIds = '';
		foreach($post['trade_sell_ids'] as $tradeSellId) {
			$tradeSellIds .= $tradeSellId . ',';
		}
		if(empty($tradeSellIds)) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'请正确选择匹配订单!']);
		}
		$tradeSellIds = rtrim($tradeSellIds, ',');

		$findFirstTradeBuy = $this -> trade::getBuyServiceInstance() -> findFirstById($id);
		if($findFirstTradeBuy['trade_buy'] -> status != 0) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'当前订单已匹配!']);
		}

		$findTradeSell = $this -> trade::getSellServiceInstance() -> find([
			'conditions' => 'status = 0 AND trade_sell_id in (' . $tradeSellIds . ')',
			'order' => 'status ASC, create_time ASC'
		]);
		if($findTradeSell['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'你选择的订单已经匹配!']);
		}

		$currentTime = time();
		$currentAmount = $findFirstTradeBuy['trade_buy'] -> amount;

		$this -> db -> begin();
		try {
			foreach($findTradeSell['trade_sell'] as $tradeSell) {
				if($currentAmount <= 0) {
					break;
				}
	
				if($tradeSell -> amount <= $currentAmount) {
					$currentAmount -= $tradeSell -> amount;

					$tradeSell -> to_user_id = $findFirstTradeBuy['trade_buy'] -> from_user_id;
					$tradeSell -> status = 2;
					$tradeSell -> last_time = $currentTime;

					if($currentAmount <= 0) {
						$tradeSell -> trade_buy_id = $findFirstTradeBuy['trade_buy'] -> trade_buy_id;

						$findFirstTradeBuy['trade_buy'] -> amount = $tradeSell -> amount;
						$findFirstTradeBuy['trade_buy'] -> trade_sell_id = $tradeSell -> trade_sell_id;
						$findFirstTradeBuy['trade_buy'] -> to_user_id = $tradeSell -> from_user_id;
						$findFirstTradeBuy['trade_buy'] -> status = 1;
						$findFirstTradeBuy['trade_buy'] -> last_time = $currentTime;
					} else {
						$findFirstTradeBuy['trade_buy'] -> amount = $currentAmount;

						$createTrade = $this -> trade::getBuyServiceInstance() -> create([
							'trade_sell_id' => $tradeSell -> trade_sell_id,
							'from_user_id' => $findFirstTradeBuy['trade_buy'] ->  from_user_id,
							'to_user_id' => $tradeSell -> from_user_id,
							'profit' => $findFirstTradeBuy['trade_buy'] -> profit,
							'amount' => $tradeSell -> amount,
							'original_amount' => $findFirstTradeBuy['trade_buy'] -> original_amount,
							'loop_number' => $findFirstTradeBuy['trade_buy'] -> loop_number,
							'create_time' => $currentTime,
							'last_time' => $currentTime,
							'status' => 1,
              'is_first' => $findFirstTradeBuy['trade_buy'] -> is_first
						]);
						if($createTrade['code'] != 0) {
							throw new \Exception($createTrade['message']);
						}

						$tradeSell -> trade_buy_id = $createTrade['trade_buy'] -> trade_buy_id;
					}

					if(!$tradeSell -> save()) {
						throw new \Exception('订单匹配失败');
					}

					$findFirstUser = $this -> user::getServiceInstance() -> findFirstById($tradeSell -> from_user_id);
					if($findFirstUser['code'] == 0) {
						$this -> SMS::getServiceInstance() -> sendSMS(['t'=>2,'account' => $findFirstUser['user'] -> account,'create_time'=>$tradeSell->create_time,'mobile'=>$findFirstUser['user'] -> cellphone]);
					}
					
				}
			}

			if(!$findFirstTradeBuy['trade_buy'] -> save()) {
				throw new \Exception('订单匹配失败');
			}

			$findFirstUser = $this -> user::getServiceInstance() -> findFirstById($findFirstTradeBuy['trade_buy'] -> from_user_id);
			if($findFirstUser['code'] == 0) {
				$this -> SMS::getServiceInstance() -> sendSMS(['t'=>1,'account' => $findFirstUser['user'] -> account,'create_time'=>$findFirstTradeBuy['trade_buy']->create_time,'mobile'=>$findFirstUser['user'] -> cellphone]);
			}

			$this -> db -> commit();
		} catch(\Exception $e) {
			$this -> db -> rollback();

			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
		}
		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'匹配成功']);
	}

	public function cancalAction($id) {
		$findFirstTradeBuy = $this -> trade::getBuyServiceInstance() -> findFirstById($id);
		if($findFirstTradeBuy['trade_buy'] -> status == 0) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'当前订单未匹配!']);
		}

		$findFirstTradeSell = $this -> trade::getSellServiceInstance() -> findFirstById($findFirstTradeBuy['trade_buy'] -> trade_sell_id);
		if($findFirstTradeSell['trade_sell'] -> status == 0) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'当前订单未匹配!']);
		}

		$this -> db -> begin();
		try {
			$findFirstTradeBuy['trade_buy'] -> trade_sell_id = 0;
			$findFirstTradeBuy['trade_buy'] -> to_user_id = 0;
			$findFirstTradeBuy['trade_buy'] -> status = 0;
			if(!$findFirstTradeBuy['trade_buy'] -> save())  { throw new \Exception('取消失败'); }

			$findFirstTradeSell['trade_sell'] -> trade_buy_id = 0;
			$findFirstTradeSell['trade_sell'] -> to_user_id = 0;
			$findFirstTradeSell['trade_sell'] -> status = 0;
			if(!$findFirstTradeSell['trade_sell'] -> save())  { throw new \Exception('取消失败'); }

			$this -> db -> commit();
		} catch(\Exception $e) {
			$this -> db -> rollback();

			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'取消成功']);
	}
	
	public function cancal0Action($id) {
		$findFirstTradeBuy = $this -> trade::getBuyServiceInstance() -> findFirst([
			'conditions' => 'trade_buy_id = ' . $id
		]);
		if($findFirstTradeBuy['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$findFirstTradeBuy['code'],'msg'=>$findFirstTradeBuy['message']]);
		}
		if($findFirstTradeBuy['trade_buy'] -> status != 0) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'订单操作错误!']);
		}

		if($findFirstTradeBuy['trade_buy'] -> amount < 10000) {
			$priceTrade = 1;
		} else if($findFirstTradeBuy['trade_buy'] -> amount >= 10000) {
			$priceTrade = 2;
		} else {
			$priceTrade = 0;
		}

		$this -> db -> begin();
		try {
			$serviceTrade = $this -> user::getWalletServiceInstance() -> updateIncAmount(['type'=>4,'amount'=>$priceTrade,'user_id'=>$findFirstTradeBuy['trade_buy'] -> from_user_id]);
			if($serviceTrade['code'] != 0) { throw new \Exception('取消失败'); }

			$findFirstTradeBuy['trade_buy'] -> trade_sell_id = 0;
			$findFirstTradeBuy['trade_buy'] -> to_user_id = 0;
			$findFirstTradeBuy['trade_buy'] -> status = 7;
			$findFirstTradeBuy['trade_buy'] -> last_time = time();
			if(!$findFirstTradeBuy['trade_buy'] -> save())  { throw new \Exception('取消失败'); }

			$this -> db -> commit();
		} catch(\Exception $e) {
			$this -> db -> rollback();

			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'取消成功']);
	}
}